/*
 * @Copyright: Copyright (c) 2030 吴周海
 * @Author: wzh200x@126.com
 * @Date: 2025-10-10 11:35:00
 * @LastEditors: wzh200x@126.com
 * @LastEditTime: 2025-10-13 16:50:44
 * @FilePath: \gogamewebserver\goGameWebServer\internal\model\entity\centerModel.go
 * @Description: Center 实体模型
 */
package entity

import (
	"encoding/json"
	"goGameWebServer/internal/common/logger"
	"goGameWebServer/internal/defines/cerror"
	"goGameWebServer/internal/defines/dataType"
	"goGameWebServer/internal/interfaces"
	"goGameWebServer/internal/manager/databasemanager"
	"time"

	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/util/gmeta"
)

type CenterModelData struct {
	gmeta.Meta `orm:"table: center"`
	Id         dataType.TypeDataBaseId `orm:"id"`                     // 主键ID
	Account    string                  `orm:"account"`                // 账号
	Data       string                  `orm:"data"`                   // 账号角色区服信息
	CreateTime time.Time               `orm:"createTime, insertTime"` // 创建时间
	LastTime   time.Time               `orm:"lastTime,updateTime" `   // 登出时间
}

func (d *CenterModelData) Reset() {
	d.Id = 0
	d.Account = ""
	d.Data = ""
	d.CreateTime = time.Now()
	d.LastTime = time.Now()
}

type CenterModel struct {
	EntityModel
}

func (m *CenterModel) LoadEntityDataFromDB(records interface{}) error {
	base, err := databasemanager.ManagerDatabase().DefaultDataBase()
	if err != nil {
		return err
	}
	if entityData, ok := m.EntityData.(*CenterModelData); ok {
		one, err := base.GetDb().Model(m.Template).Where("account", entityData.Account).One()
		if err != nil {
			return err
		}
		if one == nil {
			return m.Create()
		}
		_ = one.Struct(m.EntityData)
		m.SetEntityDBID(entityData.Id)
		return nil
	}
	return gerror.NewCodef(gcode.New(cerror.ERROR_ENTITY_PROPERTY_INVALID, "", nil), "center model data is invalid")
}

func (m *CenterModel) Create() error {
	if entityData, ok := m.EntityData.(*CenterModelData); ok {
		severs := make([]int, 0)
		entityData.CreateTime = time.Now()
		entityData.LastTime = time.Now()
		sJson, _ := json.Marshal(severs)
		entityData.Data = string(sJson)
		err := m.CreateDataToDB()
		entityData.Id = m.EntityDBID
		if err != nil {
			return err
		}
		logger.LoggerIns().Debug("create center success")
		return nil
	}
	return gerror.NewCodef(gcode.New(cerror.ERROR_ENTITY_PROPERTY_INVALID, "", nil), "center model create fail, data is invalid")
}

func NewCenterModel(name string) interfaces.IEntityModel {
	m := &CenterModel{
		EntityModel: NewEntityModel(name),
	}
	m.SetEntityData(&CenterModelData{
		Id:         0,
		Account:    "",
		Data:       "",
		CreateTime: time.Now(),
		LastTime:   time.Now(),
	})
	m.SetTemplate(m.EntityData)
	return m
}
